#include "soft_timer.h"

// 定义定时器数组
static soft_timer_t timers[MAX_TIMERS];

// 初始化定时器管理器
void soft_timer_init(void)
{
    for (int i = 0; i < MAX_TIMERS; i++) {
        timers[i].active = false;
    }
}

// 创建一个定时器（不启动）
soft_timer_t* soft_timer_create(uint32_t timeout_ms, soft_timer_mode_t mode,
                                soft_timer_callback_t cb, void *arg)
{
    for (int i = 0; i < MAX_TIMERS; i++) {
        if (!timers[i].active) {
            timers[i].timeout = timeout_ms;
            timers[i].mode = mode;
            timers[i].callback = cb;
            timers[i].arg = arg;
            timers[i].state = SOFT_TIMER_STOPPED;
            timers[i].active = true;
            return &timers[i];
        }
    }
    return NULL; // 没有可用定时器
}

// 启动定时器
bool soft_timer_start(soft_timer_t *timer)
{
    if (!timer || !timer->active) return false;
    timer->start_time = HAL_GetTick();
    timer->state = SOFT_TIMER_RUNNING;
    return true;
}

// 停止定时器
bool soft_timer_stop(soft_timer_t *timer)
{
    if (!timer || !timer->active) return false;
    timer->state = SOFT_TIMER_STOPPED;
    return true;
}

// 删除定时器
void soft_timer_delete(soft_timer_t **timer)
{
    if (timer && *timer) {
        soft_timer_stop(*timer);
        (*timer)->active = false;
        *timer = NULL;
    }
}

// 主处理函数：需周期调用（建议 1~10ms 调用一次）
void soft_timer_process(void)
{
    uint32_t current_tick = HAL_GetTick();
    soft_timer_t *t;

    for (int i = 0; i < MAX_TIMERS; i++) {
        t = &timers[i];
        if (!t->active || t->state != SOFT_TIMER_RUNNING) continue;

        // 判断是否超时（考虑 32 位溢出）
        if ((current_tick - t->start_time) >= t->timeout) {
            if (t->callback) {
                t->callback(t->arg);  // 执行回调
            }

            if (t->mode == SOFT_TIMER_PERIODIC) {
                // 周期性：重新设置起始时间（补偿延迟）
                t->start_time = current_tick;
                // 注意：如果回调耗时长，可能连续触发，可改为 += timeout 防抖
            } else {
                t->state = SOFT_TIMER_STOPPED;
            }
        }
    }
}